package com.xnx.bincker.leader.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.xnx.bincker.leader.core.domain.IdEntity;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.springframework.security.core.GrantedAuthority;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Null;
import java.util.Objects;
import java.util.Set;

/**
 * 角色
 */
@Entity
@Data
public class Role extends IdEntity implements GrantedAuthority {
	private static final long serialVersionUID = -1470265171733896764L;
	/**
	 * 角色名称
	 */
	@Insert
	@Update
	@Search
	@Column(nullable = false)
	@NotBlank(message = "角色名称不能为空", groups = {ValidGroup.Insert.class, ValidGroup.Update.class})
	@Length(min = 2, message = "角色名称太短", groups = {ValidGroup.Insert.class, ValidGroup.Update.class})
	private String name;

	@Insert
    @Update
    @NotBlank(message = "角色代码不能为空", groups = {ValidGroup.Insert.class, ValidGroup.Update.class})
	@Column(nullable = false, unique = true)
	private String code;

    @Insert
    @Update
    @Search
	private String remark;

    @Insert
    @Update
	@ManyToMany
	private Set<Authority> authorities;

	@Override
    @JsonIgnore
	public String getAuthority() {
		return code;
	}

	public void setCode(String code) {
		code = code.toUpperCase();
		if(!code.startsWith("ROLE_")) code = "ROLE_" + code;
		this.code = code;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null) return false;
		if(o instanceof Role) {
			Role role = (Role) o;
			return Objects.equals(code, role.code);
		}else if(o instanceof String){
			String code = ((String) o).toUpperCase();
			if(!code.startsWith("ROLE_")) code = "ROLE_" + code;
			return o.equals(code);
		}
		return false;
	}

	@Override
	public int hashCode() {
		if(code == null) return super.hashCode();
		return code.hashCode();
	}

	public String toString(){
	    return code;
    }
}
